package play.coroutine.basics

import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext


suspend fun run(): Boolean {
    return withContext(Dispatchers.IO) {
        var count = 0
        while (count < 10) {
            try {
                val random = Math.random() + 3
                if (count < random) {
                    throw Exception("$count 小于 $random")
                } else {
                    println("$count 大于 $random")
                    return@withContext true
                }
            } catch (e: Exception) {
                println(e.message)
                count += 1
            }
        }
        return@withContext false
    }
}

fun main() = runBlocking {
    val task = async { run() }
    println(task.await())
}